package com.vue.admin.service.common.jwt;

import com.vue.admin.service.module.sys.dao.UserDAO;
import com.vue.admin.service.module.sys.entity.UserEntity;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @program: vue-admin-service
 * @description:
 * @author: zhangyangyang
 * @create: 2020-04-03 13:19
 **/
@Component
public class JwtRealm extends AuthorizingRealm {

    @Lazy
    private UserDAO userDAO;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(token);
        if (username == null) {
            throw new IncorrectCredentialsException("SERVER_TOKEN_EXPIRED");
        }

        // 查询用户信息
        UserEntity user = this.userDAO.findUserByAccount(username);
        // 账号锁定
        if(user.getStatus() == 0) {
            throw new LockedAccountException("SERVER_ACCOUNT_LOCKED");
        }

        if (! JwtUtil.verify(token, username, user.getPassword())) {
            throw new IncorrectCredentialsException("SERVER_TOKEN_EXPIRED");
        }

        return new SimpleAuthenticationInfo(user, token, this.getName());
    }
}
